package com.gpscookie.mobile;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import de.enough.polish.ui.Alert;
import de.enough.polish.ui.AlertType;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.ItemCommandListener;
import de.enough.polish.ui.MessageItem;
import de.enough.polish.ui.Spacer;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;
import de.enough.polish.util.Locale;

public class ForumListScreen extends BasicScreen implements DownloadListener, ItemCommandListener
{

	private DownloadManager dlManager = null;

	private String url = "http://gpscookie.appspot.com/mobile/forum/list";
	private JSONObject mission = null;
	
	private Timer downloadTimer = null;
	private TimerTask downloadTask = null;
	
	private int refreshSpeed = 30000;
	
	private boolean active = false;
	private String secret = "";
	
	private Command cmdPost = null;
	private Command cmdRefresh = null;
	private Command cmdView = null;
	
	private JSONArray items = null;
	
	public ForumListScreen(String title, GPSCookie globalClass) {
		super(title, globalClass);
		this.dlManager = new DownloadManager();
		this.cmdBack = new Command(Locale.get("BACK"), Command.SCREEN, 20);		
		this.addCommand(this.cmdBack);	
		this.cmdPost = new Command(Locale.get("POST"), Command.SCREEN, 30);
		this.addCommand(this.cmdPost);
		this.cmdRefresh = new Command(Locale.get("REFRESH"), Command.SCREEN, 40);
		this.addCommand(this.cmdRefresh);		
		this.parentScreen = GPSCookie.viewScreen;		
		this.appendAd();
		this.downloadTimer = new Timer();		
		
		this.cmdView = new Command(Locale.get("VIEW"), Command.ITEM, 30);
	}

	class DownloadTask extends TimerTask {
		public void run() {
			if (active) {
				download();
			}
		}	
	}
	
	public void commandAction(Command arg0, Displayable arg1) {
		if (arg0 == cmdBack) {
			this.active = false;
			this.goBack();			
		} else if (arg0 == cmdPost) {
			this.active = false;
			this.globalClass.forumPost(mission, this.secret);
		} else if (arg0 == cmdRefresh) {
			this.active = true;
			this.download();
		}
	}
	
	public void setMission(JSONObject mission, String secret) throws JSONException {
		this.cleanScreen();
		this.labInfo.setText(Locale.get("WAITMSG"));
		this.mission = mission;
		this.secret = secret;
		this.active = true;
		download();
	}
	
	public void download() {
		try {			
			String appended = url + "?mission=" + mission.getString("dbid")+"&secret=" + secret;		
			this.dlManager.download(this, appended);
			System.out.println(appended);
		} catch (Exception e) {
			
		}
	}	
	
	private void cleanScreen() {
		this.deleteAll();
		//#style infoText
		this.labInfo = new StringItem(Locale.get("STATUS"), Locale.get("OK"));
		this.append(this.labInfo);		
	}
	
	private void scheduleDownload() {
		this.downloadTask = null;
		this.downloadTask = new DownloadTask();
		try {
			this.refreshSpeed = 60000*Integer.parseInt(GPSCookie.rmsstore.get(RMSStore.REFRESHRATE,""));
		} catch (Exception e) {
			this.refreshSpeed = 30000;
		}
		if (this.refreshSpeed > 3000) {
			this.downloadTimer.schedule(this.downloadTask, this.refreshSpeed);
		}
		System.out.println("refresh: "+this.refreshSpeed);
	}
	
	public void downloadCompleted(byte[] data) {
		String str = "";
		try {
			if (data==null || data.length<=0) {
				throw new Exception("Not found.");
			}
			str = GPSCookie.http2String(data);
			JSONObject json = new JSONObject(str);
			str = json.getString("msg");
			if ("OK".equals(str.toUpperCase())) {
				JSONArray items = json.getJSONArray("items");
				this.setItems(items);
				this.scheduleDownload();
			} else {
				throw new Exception(str);
			}
		} catch (Exception e) {
			str = e.toString();
			this.labInfo.setText(str);
		}		
	}
	
	private void setItems(JSONArray items) throws Exception
	{
		this.items = items;
		this.deleteAll();
		if (items.length()==0) {
			//#style infoText
			this.labInfo = new StringItem(Locale.get("STATUS"), Locale.get("EMPTY"));
			this.append(this.labInfo);		
		}
		for (int i=0; i<items.length() && i<=7; i++) {
			JSONObject item = items.getJSONObject(i);
			String comments = item.getString("comments");
			int endIndex = comments.length();
			if (endIndex<=10) {
				endIndex = endIndex;
				comments = comments.substring(0, endIndex);
			} else {
				endIndex = 8;
				comments = comments.substring(0, endIndex);
				comments += "...";
			}			
			
			//#style recordhead
			StringItem record1 = new StringItem(item.getString("player"), item.getString("timestamp"));
			//#style recordbody
			StringItem record2 = new StringItem(String.valueOf(i), comments);
			record2.setItemCommandListener(this);
			record2.addCommand(this.cmdView);
			this.append(record1);
			this.append(record2);
		}		
	}

	public void downloadError(Exception e) {
		this.labInfo.setText(e.getMessage());	
	}

	public void downloadStatus(int percent) {
		this.labInfo.setText(String.valueOf(percent)+"%");		
	}

	public void commandAction(de.enough.polish.ui.Command arg0, Item arg1) {
		StringItem item = (StringItem)arg1;
		String id = item.getLabel();
		String text = item.getText();
		System.out.println(id+" * "+text);
		try {
			JSONObject obj = this.items.getJSONObject(Integer.parseInt(id));
			item.setText(obj.getString("comments"));
		} catch (Exception e) {
			item.setText(text);
		}
	}
}
